package dongze.com.ckdj.ui;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import dongze.com.ckdj.R;
import dongze.com.ckdj.util.MyLog;

import static android.support.v4.widget.ViewDragHelper.Callback;
import static android.support.v4.widget.ViewDragHelper.create;

/**
 * Created by fanqwz on 2017/10/16.
 */

public class SwipeToDeleteLayout extends FrameLayout {
    private static final String TAG = SwipeToDeleteLayout.class.getSimpleName();
    private static final int thresholdY = 10;
    private static final int thresholdX = 10;
    private ViewDragHelper mDragHelper;
    private int deleteViewWidth;
    private int editViewWidth;
    private int totalViewWidth;
    private LinearLayout container;
    private Button deleteView;
    private TextView editView;
    float downX;
    float downY;
    boolean startedDetect = false;

    public enum State {OPEN, CLOSE}

    private State state = State.CLOSE;


    public SwipeToDeleteLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        deleteViewWidth = getContext().getResources().getDimensionPixelSize(R.dimen.swipe_to_delete_view_width);
        editViewWidth = getContext().getResources().getDimensionPixelSize(R.dimen.swipe_to_delete_view_width);
        totalViewWidth = editViewWidth + deleteViewWidth;
        deleteView = new Button(context);
        deleteView.setText("删除");
        deleteView.setGravity(Gravity.CENTER);
        deleteView.setBackgroundColor(0xFFFF0000);
        editView = new TextView(context);
        editView.setText("编辑");
        editView.setGravity(Gravity.CENTER);
        editView.setBackgroundColor(0xFF00FFFF);
        container = new LinearLayout(getContext());
        container.setOrientation(LinearLayout.HORIZONTAL);
        container.addView(editView, new LinearLayout.LayoutParams(editViewWidth, ViewGroup.LayoutParams.MATCH_PARENT));
        ((LinearLayout.LayoutParams) editView.getLayoutParams()).gravity = Gravity.CENTER;
        container.addView(deleteView, new LinearLayout.LayoutParams(deleteViewWidth, ViewGroup.LayoutParams.MATCH_PARENT));
        ((LinearLayout.LayoutParams) deleteView.getLayoutParams()).gravity = Gravity.CENTER;
        addView(container, new FrameLayout.LayoutParams(totalViewWidth, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT));
        mDragHelper = create(this, callback);
    }

    public void setState(State state) {
        this.state = state;
//        mDragHelper.abort();

        for (int i = 0; i < getChildCount(); i++) {
//            getChildAt(i).setTranslationX(0);
            mDragHelper.smoothSlideViewTo(getChildAt(i), 0, 0);
        }
    }

    public void setOnDeleteClick(OnClickListener l) {
        deleteView.setOnClickListener(l);
    }
    public void setOnEditClick(OnClickListener l) {
        editView.setOnClickListener(l);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        MyLog.d(TAG, "onInterceptTouchEvent: ");
        return mDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            downX = event.getRawX();
            downY = event.getRawY();
            startedDetect = false;
            requestDisallowInterceptTouchEvent(true);
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (startedDetect) {
                if ((event.getRawX() - downX > thresholdX && state == State.CLOSE)
                        || (event.getRawX() - downX < -thresholdX && state == State.OPEN)) {
                    requestDisallowInterceptTouchEvent(false);
                }
            } else {
                if ((Math.abs(event.getRawY() - downY) > thresholdY))
                    requestDisallowInterceptTouchEvent(false);

                if (Math.abs(event.getRawX() - downX) > thresholdX) {
                    startedDetect = true;
                }
            }
        }

        if (startedDetect)
            mDragHelper.processTouchEvent(event);

        return true;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        container.layout(getMeasuredWidth(), 0, getMeasuredWidth() + totalViewWidth, getMeasuredHeight());
    }

    @Override
    public void computeScroll() {
        if (mDragHelper.continueSettling(true)) {
            invalidate();
        }
    }

    private void doReleaseAnimation(State state) {
        this.state = state;
        int finalX = 0;
        if (state == State.OPEN) {
            finalX = -totalViewWidth;
        }

        if (mDragHelper.settleCapturedViewAt(finalX, 0)) {
            postInvalidate();
        }

    }

    Callback callback = new Callback() {
        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            return child != container;
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            left = left + dx;
            if (left < -totalViewWidth) {
                return -totalViewWidth;
            } else if (left > 0) {
                return 0;
            } else {
                return left;
            }
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            container.setTranslationX(left);
            invalidate();
        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            MyLog.d(TAG, "onViewReleased: " + releasedChild + ":" + xvel + ":" + yvel);
            if (Math.abs(xvel) > 100) {
                doReleaseAnimation((xvel < 0) ? State.OPEN : State.CLOSE);
            } else if ( -container.getTranslationX() > totalViewWidth / 2) {
                doReleaseAnimation(State.OPEN);
            }else if (-container.getTranslationX() < totalViewWidth / 2) {
                doReleaseAnimation(State.CLOSE);
            } else {
                doReleaseAnimation(state);
            }
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            return totalViewWidth;
        }
    };
}
